<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #productNo="{ model, field }">
        <JSearchSelect placeholder="请选择产品" :onChange="fetchFormSchema" v-model:value="model[field]" :dict="'t_product,name,no'" />
      </template>
      <template #iot="{ model, field }">
        <a-cascader :options="options" :load-data="loadData" :change-on-select="true" v-model:value="model[field]" multiple @change="handleChange">
        </a-cascader>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" name="QrcodeConfigModal" setup>
  import { ref, computed, unref, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { saveOrUpdate } from '../QrcodeConfig.api';
  import { defHttp } from '/@/utils/http/axios';
  import JSearchSelect from '@/components/Form/src/jeecg/components/JSearchSelect.vue';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const options = ref([]);
  // iot数据，编辑时候使用
  const iotData = ref([]);
  const formSchema = ref([
    // TODO 主键隐藏字段，目前写死为ID
    {
      label: '',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      label: '产品',
      field: 'productNo',
      component: 'JSearchSelect',
      slot: 'productNo',
      componentProps: {
        dict: 't_product,name,no',
      },
      dynamicRules: ({ model, schema }) => {
        return [{ required: true, message: '请选择产品!' }];
      },
    },
  ]);
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, appendSchemaByField, resetSchema }] = useForm({
    //labelWidth: 150,
    schemas: formSchema.value,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
  const fetchFormSchema = async (productNo) => {
    try {
      const response = await defHttp.get({ url: '/qrcodeConfig/getConfigList', params: { productNo: productNo } });
      let data = response;
      // 重置表单
      reset();

      // 生成结构
      await data.forEach((item) => {
        appendSchemaByField({
          field: 'divider-basic',
          component: 'Divider',
          label: item['name'],
        });
        let option = item['data'];
        if (option) {
          option.forEach((o, index) => {
            let colProps = {
              span: 6,
            };

            // 如果是第1个、第5个、第9个...等
            if (index % 4 === 0) {
              colProps.offset = 1; // 对于这些特定的元素，设置offset为1
            }
            // 如果是第4个、第8个、第12个...等
            else if ((index + 1) % 4 === 0) {
              colProps.span = 5; // 对于这些特定的元素，设置span为5
            }
            if (o.slot) {
              if (o.slot == 'iot') {
                colProps.span = 16;
              }
              appendSchemaByField({
                field: o.key,
                component: 'Input',
                label: '',
                colProps: colProps,
                slot: o.slot,
              });
              setFieldsValue({ [o.key]: [] });
              formSchema.value.push({
                field: o.key,
                component: 'Input',
                label: '',
                colProps: colProps,
                slot: o.slot,
              });
            } else {
              appendSchemaByField({
                field: o.key,
                component: 'Checkbox',
                label: '',
                colProps: colProps,
                renderComponentContent: o.name,
              });
              setFieldsValue({ [o.key]: true });
            }
          });
        }
      });
      await fetchIotUser();
    } catch (error) {
      console.error('获取formSchema失败:', error);
    }
  };
  const fetchIotUser = async () => {
    try {
      const response = await defHttp.get({ url: '/thingsUser/list', });
      options.value = response.records;
      let op = [];
      op = response.records.map((item) => ({
        label: item.userName,
        value: item.id,
        isLeaf: false,
      }));
      options.value = op;
      // 如果存在参数，则是编辑
      if (iotData.value){
        // console.log(options.value, iotData.value)
        for (let i = 0; i < options.value.length; i++){
          // if (options.value[i].value === iotData.value.split(",")[0]){
            loadData([options.value[i]]);
            // break;
          // }
        }
      }
    } catch (error) {
      console.error('获取formSchema失败:', error);
    }
  };
  const handleChange = (value, selectedOptions) => {
    let arr = []
    selectedOptions.forEach((item, index) => {
      if (item.length == 1) {
        let opt = item[0];
        opt.children.forEach(val => {
          arr.push({account: opt.value, deviceId: val.value})
        })
      } else {
        arr.push({account: value[index][0], deviceId: value[index][1]})
      }
    })
    iotData.value = arr;
  }
  // 重置表单
  async function reset() {
    await resetSchema([
      // TODO 主键隐藏字段，目前写死为ID
      {
        label: '',
        field: 'id',
        component: 'Input',
        show: false,
      },
      {
        label: '产品',
        field: 'productNo',
        component: 'JSearchSelect',
        slot: 'productNo',
        componentProps: {
          dict: 't_product,name,no',
        },
        dynamicRules: ({ model, schema }) => {
          return [{ required: true, message: '请选择产品!' }];
        },
      },
    ]);
  }
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // 重置表单
    reset();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      //重置表单
      await resetFields();
      //表单赋值
      if (data.record.qrcodeConfigOptions) {
        data.record.qrcodeConfigOptions.forEach((item) => {
          data.record[item.keyInfo] = item.checked === 1;
          if (item.keyInfo === 'iotData' && item.params) {
            var arr = [];
            JSON.parse(item.params).map(sec => {
              arr.push(sec.account)
              arr.push(sec.deviceId)
            })
            // iotData.value = arr.join(',');
            data.record[item.keyInfo] = arr.reduce((acc, curr, index) => {
                if (index % 2 === 0) {
                    acc.push([curr, arr[index + 1]]);
                }
                return acc;
            }, []);//[['1701119592722149377', 'b72ffc50-5121-11ee-bd1c-5b5432e10ef4'], ['1706510519468896258', '994e9760-5cd8-11ee-bd1c-5b5432e10ef4']];
          }
        });
      }
      await fetchFormSchema(data.record.productNo);
      await setFieldsValue({
        ...data.record,
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
  //表单提交事件
  async function handleSubmit(v: any) {
    try {
      let values = await validate();
      
      setModalProps({ confirmLoading: true });
      let qrcodeConfigOptions = [];
      
      for (let key in values) {
        if (key === 'iotData') {
          // const iotData = values[key].split(',');
          // console.log(iotData, options.value)
          // const arr = iotData.reduce((acc: { account: any; deviceId: any; }[], curr: any, index: number) => {
          //     if (index % 2 === 0) {
          //       acc.push({ account: curr, deviceId: iotData[index + 1] });
          //     }
          //     return acc;
          // }, []);
          // console.log(iotData, arr);
          values[key] = JSON.stringify(iotData.value)
        }
        if (key !== 'name' && key !== 'productNo') {
          let option = {
            keyInfo: key,
            checked: values[key] ? 1 : 0,
            params: values[key],
          };
          qrcodeConfigOptions.push(option);
        }
      }

      values.qrcodeConfigOptions = qrcodeConfigOptions;
      // console.log(values)
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 加载下拉框子集数据
  const loadData = async (selectedOptions: string | any[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    try {
      const response = await defHttp.get({
        url: '/thingsUserDevice/list',
        params: Object.assign({ pageSize: 1000, pageNo: 1 }, { id: targetOption.value }),
      });

      targetOption.loading = false;
      targetOption.children = response.data.map((item) => ({
        label: item.name,
        value: item.id.id,
        isLeaf: !!targetOption.value,
      }));
    } catch (error) {
      targetOption.loading = false;
      console.error('加载级联数据失败:', error);
    }
  };
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
